//
//  TZYHomeViewController.m
//  Moment
//
//  Created by dllo on 15/12/23.
//  Copyright © 2015年 谭泽源. All rights reserved.
//

#import "TZYHomeViewController.h"
#import "TZYWheelView.h"


@interface TZYHomeViewController ()<UITableViewDataSource, UITableViewDelegate, TZYPictureCellDelegate, UIScrollViewDelegate>

@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) TZYHomeData *homeData;
@property (nonatomic, assign) NSInteger nextPage;
@property (nonatomic, assign) BOOL isUpLoad;  /**< 标记上拉操作还是下拉操作，yes为上拉 */
@property (nonatomic, strong) NSMutableArray *allArray;      /**<所有model数组*/
@property (nonatomic, strong) TZYWheelView *wheelView;
@property (nonatomic, strong) UIScrollView *scrollV;
@property (nonatomic, strong) NSMutableArray *subViewArr;
@property (nonatomic, strong) UITableView *debrisTableView;
@property (nonatomic, strong) TZYDebrisTableViewController *tableViewController;
@property (nonatomic, strong) UIImageView *rightImageView;
@property (nonatomic, strong) UIImageView *rightImageView1;
@property (nonatomic, copy) NSString *myTitle;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) UIView *lineView1;
@property (nonatomic, retain)NSMutableArray *refreshPicArr;

@end

@implementation TZYHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //防止晃动(防止scrollV自适应导航栏)
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setAutomaticallyAdjustsScrollViewInsets:NO];
    

    
    self.refreshPicArr = [NSMutableArray array];
    for (int i = 0; i < 29; i++) {
        NSString *imageName = [NSString stringWithFormat:@"refresh%d.png",i];
        UIImage *image = [UIImage imageNamed:imageName];
        CGSize size = CGSizeMake(20, 20);
        UIImage *newImage = [SelfAdaption image:image byScalingToSize:size];
        [_refreshPicArr addObject:newImage];
        [[Singleton shareDataBase].animationArray addObject:newImage];
    }
    
    //给数组开空间
    self.allArray = [NSMutableArray array];
    
    //创建navigationBar 的控件
    [self createBarButtonAndImage];
    
    
    //创建scrollView(2个页面)
    [self createScrollView];
    
   
}





#pragma mark-创建navigationBar上控件
- (void)createBarButtonAndImage
{
    //创建一个右边的父视图rightView
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightView];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
    
    //碎片图片按钮
    self.rightImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 25, 22)];
    self.rightImageView.image = [UIImage imageNamed:@"iconfont-iconfonticonfontfangwu-2.png"];
    [rightView addSubview:self.rightImageView];
    
    
    //底部view
    self.lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 28, 25, 2)];
    self.lineView.backgroundColor = [UIColor blackColor];
    [rightView addSubview:self.lineView];
    self.lineView.hidden = YES;
    
    

    //首页图片按钮
    self.rightImageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(46, 0, 25, 22)];
    self.rightImageView1.image = [UIImage imageNamed:@"iconfont-xiangqing-3.png"];
    [rightView addSubview:self.rightImageView1];
    
    //底部view
    self.lineView1 = [[UIView alloc] initWithFrame:CGRectMake(46, 28, 25, 2)];
    self.lineView1.backgroundColor = [UIColor blackColor];
    [rightView addSubview:self.lineView1];
    
    
    //以下是分别给两个图片添加轻拍手势
    UITapGestureRecognizer *tapGR1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGR1:)];
    self.rightImageView.userInteractionEnabled = YES;
    [self.rightImageView addGestureRecognizer:tapGR1];
    
    
    UITapGestureRecognizer *tapGR2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGR2:)];
    self.rightImageView1.userInteractionEnabled = YES;
    [self.rightImageView1 addGestureRecognizer:tapGR2];

}



#pragma mark-轻拍手势执行方法
- (void)tapGR1:(UIGestureRecognizer *)sender
{
    self.scrollV.contentOffset = CGPointMake(0, 0);
    self.rightImageView.image = [UIImage imageNamed:@"iconfont-iconfonticonfontfangwu.png"];
    self.rightImageView1.image = [UIImage imageNamed:@"iconfont-xiangqing-4"];
    self.headNameLabel.text = @"碎片";
    
    self.lineView1.hidden = YES;
    self.lineView.hidden = NO;
}

- (void)tapGR2:(UIGestureRecognizer *)sender
{
    self.scrollV.contentOffset = CGPointMake(SCREEN_WIDTH, 0);
    self.rightImageView.image = [UIImage imageNamed:@"iconfont-iconfonticonfontfangwu-2.png"];
    self.rightImageView1.image = [UIImage imageNamed:@"iconfont-xiangqing-3.png"];
    self.headNameLabel.text = self.myTitle;
    
    self.lineView1.hidden = NO;
    self.lineView.hidden = YES;
}




#pragma mark-滑动页面控制上面的图片转变
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
    //NSLog(@"scrollView.contentOffset.x= %f", self.scrollV.contentOffset.x);
    
    if (self.scrollV.contentOffset.x == SCREEN_WIDTH) {
        self.rightImageView.image = [UIImage imageNamed:@"iconfont-iconfonticonfontfangwu-2.png"];
        self.rightImageView1.image = [UIImage imageNamed:@"iconfont-xiangqing-3.png"];
        
        self.headNameLabel.text = self.myTitle;
        
        self.lineView1.hidden = NO;
        self.lineView.hidden = YES;
        
    }
    
    if (self.scrollV.contentOffset.x == 0)
    {
        self.rightImageView.image = [UIImage imageNamed:@"iconfont-iconfonticonfontfangwu.png"];
        self.rightImageView1.image = [UIImage imageNamed:@"iconfont-xiangqing-4"];
        
        self.headNameLabel.text = @"碎片";
        
        self.lineView1.hidden = YES;
        self.lineView.hidden = NO;
        
        //NSLog(@"减速停止");
        
    }
    
}



#pragma mark-创建scrollView
- (void)createScrollView
{
    self.scrollV = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 44, SCREEN_WIDTH, SCREEN_HEIGHT - 44)];
    [self.view addSubview:self.scrollV];
    
    //左右滑动
    self.scrollV.contentSize = CGSizeMake(SCREEN_WIDTH * 2, SCREEN_HEIGHT - 44);
    self.scrollV.contentOffset = CGPointMake(SCREEN_WIDTH, 0);
    //设置按页滑动
    self.scrollV.pagingEnabled = YES;
    //取消边界反弹效果
    self.scrollV.bounces = NO;
    self.scrollV.showsHorizontalScrollIndicator = NO;
    self.scrollV.delegate = self;
    
    //用来存子view的
    self.subViewArr = [NSMutableArray array];
    
    for (int i = 0; i < 2; i++) {
        //水平方向的
        UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * i, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 44)];
        
        [self.subViewArr addObject:subView];
        [self.scrollV addSubview:subView];
        
        
        //如果是第一页的话,创建的是碎片页面
        if (i == 0) {

            self.tableViewController = [[TZYDebrisTableViewController alloc] init];
            [self addChildViewController:self.tableViewController];
            [subView addSubview:self.tableViewController.view];
            
        }
        //如果是第二页,则创建主首页
        if (i == 1) {
            
#pragma mark-创建tableView 和 网络请求数据
            [self createTableView];
            [self addHeaderRefresh];
            [self addFooterRefresh];
        }
    }
    
   
    
}




#pragma mark -- 设置下拉刷新
//-(void)addHeaderRefresh
//{
//    //当下拉时候会触发该方法
//    self.myTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        NSLog(@"下拉");
//        
//        self.nextPage = 0;// 记录页码的
//        self.isUpLoad = NO;//标记为下拉操作
//        // 重新请求数据
//        [self getAFNetWorkingData];
//        
//    }];
//    
//    // 进到应用自动刷新(可以放在viewdidload)
//    [self.myTableView.mj_header beginRefreshing];
//}


- (void)addHeaderRefresh
{
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshHeaderAction)];
     [header setImages:[Singleton shareDataBase].animationArray forState:MJRefreshStateRefreshing];
    
    
    header.lastUpdatedTimeLabel.hidden = YES;
    
    // 隐藏状态
    header.stateLabel.hidden = YES;
    
    
    self.myTableView.mj_header = header;
    
    [self.myTableView.mj_header beginRefreshing];
    

}

- (void)refreshHeaderAction
{
    self.nextPage = 0;// 记录页码的
    self.isUpLoad = NO;//标记为下拉操作
    // 重新请求数据
    [self getAFNetWorkingData];
}



//#pragma mark -- 设置上拉刷新(不加动画的)
//-(void)addFooterRefresh
//{
//    //当上拉时候触发该方法
//    self.myTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        NSLog(@"上拉");
//        
//        self.nextPage += 10;
//        self.isUpLoad = YES;
//        // 重新请求数据
//        [self getAFNetWorkingDataUpLoad];
//       
//    }];
//    
//}


#pragma mark -- 设置上拉刷新
-(void)addFooterRefresh
{
    //    设置上拉刷新动画
    MJRefreshAutoGifFooter  *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshAction)];
    [footer setImages:[Singleton shareDataBase].animationArray forState:MJRefreshStateRefreshing];
    footer.refreshingTitleHidden = YES;
    footer.stateLabel.hidden = YES;
    
    self.myTableView.mj_footer = footer;
    [self.myTableView.mj_footer beginRefreshing];
}
-(void)refreshAction{
    NSLog(@"上拉");
    self.nextPage += 10;
    self.isUpLoad = YES;
    // 重新请求数据
    [self getAFNetWorkingDataUpLoad];
}







#pragma mark-网络请求数据(下拉)
- (void)getAFNetWorkingData
{
    NSString *urlStr = @"http://api2.pianke.me/pub/today";
    NSString *para = [NSString stringWithFormat:@"auth=&client=1&deviceid=DC7311B8-4DFE-4BC2-99D9-565BF1215670&limit=10&start=0&version=3.0.6"];
    
   
    [GetData postUrl:urlStr body:para result:HXJSON requestStyle:HXRequestString headerFile:nil success:^(id result) {
        
        if (self.isUpLoad == NO) {
            //说明是下拉，就要清空数组中的数据
            [self.allArray removeAllObjects];
        }
        
        NSMutableDictionary *bigDic = [result objectForKey:@"data"];
        for (NSMutableDictionary *dic in [bigDic objectForKey:@"list"]) {
            TZYHomeData *homeData = [[TZYHomeData alloc] init];
            [homeData setValuesForKeysWithDictionary:dic];
            [self.allArray addObject:homeData];
        }
        NSMutableArray *caArray = [bigDic objectForKey:@"carousel"];
        [self.wheelView presentToArray:caArray];
        
        self.myTitle = [bigDic objectForKey:@"date"];
        self.headNameLabel.text = self.myTitle;
        
        [self.myTableView.mj_header endRefreshing];
        [self.myTableView reloadData];
        
        
        
    } failure:^(NSError *error) {
        
        
    }];
}


#pragma mark-上拉
- (void)getAFNetWorkingDataUpLoad
{
    NSString *urlStr = @"http://api2.pianke.me/pub/today";
    NSString *para = [NSString stringWithFormat:@"auth=&client=1&deviceid=DC7311B8-4DFE-4BC2-99D9-565BF1215670&limit=10&start=%ld&version=3.0.6", self.nextPage];
    
    [GetData postUrl:urlStr body:para result:HXJSON requestStyle:HXRequestString headerFile:nil success:^(id result) {
        NSMutableDictionary *bigDic = [result objectForKey:@"data"];
        for (NSMutableDictionary *dic in [bigDic objectForKey:@"list"]) {
            TZYHomeData *homeData = [[TZYHomeData alloc] init];
            [homeData setValuesForKeysWithDictionary:dic];
            [self.allArray addObject:homeData];
        }
        NSMutableArray *caArray = [bigDic objectForKey:@"carousel"];
        
        if (caArray.count != 0) {
            [self.wheelView presentToArray:caArray];
        }
        
        self.myTitle = [bigDic objectForKey:@"date"];
        self.headNameLabel.text = self.myTitle;
        
        [self.myTableView.mj_footer endRefreshing];
        [self.myTableView reloadData];
        
        
        
    } failure:^(NSError *error) {
        
        
    }];

}



#pragma mark-创建tableView
- (void)createTableView
{
    self.myTableView = [[UITableView alloc] init];
    UIView *tableView = [self.subViewArr objectAtIndex:1];
    [tableView addSubview:self.myTableView];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    //self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myTableView.showsVerticalScrollIndicator = NO;
    self.myTableView.backgroundColor = [UIColor whiteColor];
   
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(@0);
    }];
    

   
#pragma mark-创建轮播图
    self.wheelView = [[TZYWheelView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, (SCREEN_HEIGHT - 64 ) / 3)];
    
    self.myTableView.tableHeaderView = self.wheelView;
    
    [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.myTableView registerClass:[TZYMusicCell class] forCellReuseIdentifier:@"TZYMusicCell"];
    [self.myTableView registerClass:[TZYSoundCell class] forCellReuseIdentifier:@"TZYSoundCell"];
    [self.myTableView registerClass:[TZYTopicCell class] forCellReuseIdentifier:@"TZYTopicCell"];
    [self.myTableView registerClass:[TZYPictureCell class] forCellReuseIdentifier:@"TZYPictureCell"];
    [self.myTableView registerClass:[TZYNotitleCell class] forCellReuseIdentifier:@"TZYNotitleCell"];
    [self.myTableView registerClass:[TZYHomeDataCell class] forCellReuseIdentifier:@"TZYHomeDataCell"];
    
}



#pragma mark-各种Cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (!(self.scrollV.contentOffset.x == SCREEN_WIDTH)) {
        return 200;
    } else {
        TZYHomeData *homeData = [self.allArray objectAtIndex:indexPath.row];
        if ([homeData.name isEqualToString:@"话题"]) {
            return TopicCellHeight ;
            
        }else if([homeData.name isEqualToString:@"碎片"]){
            return NotitleCellHeight;
            
        }else if([homeData.name isEqualToString:@"Ting"]){
            return SoundCellHeight;
            
        }else if([homeData.name isEqualToString:@"音乐"]){
            return SCREEN_HEIGHT / 3;
            
        }else if ([homeData.name isEqualToString:@"插画"] || [homeData.name isEqualToString:@"摄影"]){
            return PictureCellHeight;
        }else{
            return HomeDataCellHeight;
        }

    }
    
    
    
   
}


#pragma mark-tableView 的几个方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.allArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
#pragma mark 赋值
        TZYHomeData *homeData = [self.allArray objectAtIndex:indexPath.row];
        
        if ([homeData.name isEqualToString:@"音乐"]) {
            
            static NSString *identifier = @"TZYMusicCell";
            TZYMusicCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.homeData = homeData;
            return cell;
            
        } else if ([homeData.enname isEqualToString:@"Sound"]) {
            
            static NSString *identifier = @"TZYSoundCell";
            TZYSoundCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.homeData = homeData;
            
            return cell;
            
        } else if ([homeData.name isEqualToString:@"话题"]) {
            static NSString *identifier = @"TZYTopicCell";
            TZYTopicCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.homeData = homeData;
            
            return cell;
            
            
        } else if ([homeData.name isEqualToString:@"插画"] || [homeData.name isEqualToString:@"摄影"]) {
            static NSString *identifier = @"TZYPictureCell";
            TZYPictureCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            cell.pictureCellDeleage = self;
            
            cell.homeData = homeData;
            
            return cell;
            
            
        } else if ([homeData.name isEqualToString:@"碎片"]) {
            static NSString *identifier = @"TZYNotitleCell";
            TZYNotitleCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.homeData = homeData;
            
            return cell;
            
            
        } else  {
            static NSString *identifier = @"TZYHomeDataCell";
            TZYHomeDataCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            
            
            cell.homeData = homeData;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
        }

  
    
    return nil;
}

#pragma mark- 点击cell触发
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    TZYHomeDetailViewController *homeDetailVC = [[TZYHomeDetailViewController alloc]init];
    TZYHomeData *homeData = [self.allArray objectAtIndex:indexPath.row];
    if ([homeData.enname isEqualToString:@"Sound"]) {
        
        DHMusicPlayerViewController *musicVC = [DHMusicPlayerViewController shareMusicPlayerViewController];
        
        musicVC.homeData = homeData;

        [self.navigationController pushViewController:musicVC animated:YES];
        
        
    }else{
        homeDetailVC.titleStr = homeData.title;
        homeDetailVC.detaId = homeData._id;
        [self.navigationController pushViewController:homeDetailVC animated:YES];
    }
    
    
}


#pragma mark - 协议方法 (模态到相册)
-(void)presentToViewController:(NSInteger)number ImgArray:(NSMutableArray *)imgArray
{
    
    TZYPhotoViewController *photoVC = [[TZYPhotoViewController alloc]init];
    
    photoVC.photoArray = imgArray;
    photoVC.photoNumber = number - 1000;
    [photoVC setModalTransitionStyle: UIModalTransitionStyleCrossDissolve];
    [self.view.window.rootViewController presentViewController:photoVC animated:YES completion:^{
        

    }];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
